import asyncio
from bilibili_api import live
from bilibili_api.utils.danmaku import Danmaku

class DanmakuSender:
    def __init__(self, room_id, access_token=None):
        self.room_id = room_id
        self.access_token = access_token
        self.room = live.LiveDanmaku(room_id)
        self.user = None

    async def send(self, text: str):
        # 发送弹幕，需登录态
        import logging
        logger = logging.getLogger("bilibili.danmaku_sender")
        if not self.user:
            from bilibili_api import Credential, user
            import os, yaml
            # 优先尝试从配置文件读取cookie
            cookie_path = os.path.join(os.path.dirname(__file__), '../../config/config.yaml')
            sessdata = bili_jct = dedeuserid = None
            if os.path.exists(cookie_path):
                with open(cookie_path, 'r', encoding='utf-8') as f:
                    config = yaml.safe_load(f)
                    cookies = config.get('bilibili', {}).get('cookie', {})
                    sessdata = cookies.get('SESSDATA')
                    bili_jct = cookies.get('bili_jct')
                    dedeuserid = cookies.get('DedeUserID')
            if sessdata and bili_jct and dedeuserid:
                cred = Credential(sessdata, bili_jct, dedeuserid)
                # 先获取自己的uid
                try:
                    info = await user.get_self_info(cred)
                    uid = info.get('mid')
                    self.user = user.User(uid=uid, credential=cred)
                    logger.info(f"cookie有效，已登录用户: {info.get('name', info.get('uname', '未知'))} (UID: {uid})")
                except Exception as e:
                    logger.error(f"cookie无效或已过期，无法发送弹幕: {e}")
                    import traceback
                    logger.error(traceback.format_exc())
                    # logger.error(f"[ERROR] cookie无效或已过期，无法发送弹幕！请重新获取cookie并填写到config.yaml。异常: {e}")
                    return
            else:
                # logger.error("未检测到cookie，无法自动扫码登录。请手动配置cookie到config.yaml的bilibili.cookie下！")
                logger.error("未检测到cookie，无法发送弹幕。请手动配置cookie到config.yaml的bilibili.cookie下！")
                return
        # 只要self.user有效就发送弹幕
        danmaku = Danmaku(text)
        room = live.LiveRoom(self.room_id, credential=self.user.credential)
        await room.send_danmaku(danmaku)
